package com.news.news.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.news.news.dao.CommentDao;
import com.news.news.modle.Comment;
import com.news.news.util.JWTUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class CommentService {
    @Resource
    CommentDao commentDao;
    @Resource
    RedisTemplate redisTemplate;


    public PageInfo<Comment> CommentList(@RequestBody Comment comment) {
        PageHelper.startPage(comment.getPageNum(),comment.getPageSize());
        ArrayList<Comment> commentArrayList = commentDao.commentList(comment);
//        System.out.println(roles);
        PageInfo<Comment> pageInfo = new PageInfo<>(commentArrayList);
        return pageInfo;
    }

    public void saveComment(Comment comment, String token) {
        comment.setAdminId(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        //保存信息并返回ID
        commentDao.saveComment(comment);
    }

    public void UpdateLinkState(Comment comment) {
        commentDao.UpdateCommentState(comment);
    }

    public Comment findCommentById(Integer id) {
        Comment comment = commentDao.findCommentById(id);
        return comment;
    }

    public void updateComment(Comment comment, String token) {
       comment.setAdminId(JWTUtil.getTokenInfo(token).getClaim("id").asInt());
        //修改链接信息
        commentDao.updateComment(comment);
    }
    //
    public void deleteCommentById(Integer id) {
        commentDao.deleteCommentById(id);
    }

    public List<Comment> GetCommentList(String token) {
        Integer id=JWTUtil.getTokenInfo(token).getClaim("id").asInt();
        ArrayList<Comment> arrayList=commentDao.GetCommentList(id);
        return arrayList;
    }

    /**
     * 删除用户界面的评论
     * @param token
     * @param newsid
     * @param commentId
     */
    public void deleteComment(String token, int newsid, int commentId) {
        Integer userid = JWTUtil.getTokenInfo(token).getClaim("id").asInt();
        commentDao.deleteUserComment(userid,newsid,commentId);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Integer o = (Integer)valueOperations.get("news" + newsid + ":" + "plNum");
        if(o!=null){
            if(o==1){
                redisTemplate.delete("news"+newsid+"user"+userid+"pl:");//设置一个标识
            }
                valueOperations.decrement("news" + newsid + ":" + "plNum");

        }
    }

}
